import Vue from 'vue'
import api from '../../apis'
import * as types from '../types'

let JSON = global.JSON;

export default {
	state: {
		user: JSON.parse(sessionStorage.getItem('user')),
		loginFailure: null,
		access_token: JSON.parse(sessionStorage.getItem('access_token')),
		showModifyPasswordForm: false,
        menus:[
            {
                id:0,
                name:"合作站点",
                path:"cooperation",
                component:"Cooperation",
            },
            {
                id:1,
                name:"账单明细",
                path:"bill",
                component:"Bill",
            },
        ]
	},
	getters: {
		/**
		 * 获取用户菜单
		 * @param state
		 */
		menus: state => {
			return state.menus;
		}
	},
	mutations: {
		SET_USER: (state, data = null) => {
			Vue.set(state, 'user', data);
			if (data) {
				sessionStorage.setItem('user', JSON.stringify(data));
			} else {
				sessionStorage.removeItem('user');
			}
		},
		SET_ACCESS_TOKEN: (state, token = null) => {
			Vue.set(state, 'access_token', token);
			if (token) {
				sessionStorage.setItem('access_token', JSON.stringify(token));
			} else {
				sessionStorage.removeItem('access_token');
			}
		},
		SET_LOGIN_FAILURE: (state, data = null) => {
			Vue.set(state, 'loginFailure', data);
		},
		SET_USER_AVATAR: (state, avatar) => {
			Vue.set(state.user, 'avatar', avatar);
		},
		SET_MODIFY_PASSWORD_FROM: (state, data = false) => {
			Vue.set(state, 'showModifyPasswordForm', data);
		},
	},
	actions: {
		/**
		 * 用户登录
		 * @param commit
		 * @param params
		 */
		login ({ commit }, params) {
			api.account.login(params).then(response => {
                commit(types.SET_ACCESS_TOKEN, response.data.data.access_token);
                commit(types.SET_USER, response.data.data);
			}).catch(errors => {
                commit(types.SET_LOGIN_FAILURE, errors.response.data.resultMessage);
			});
		},
        // fetchProfile ({ commit }) {
			// api.account.fetchProfile().then(response => {
			// 	commit(types.SET_USER, response.data);
			// });
        // },
		/**
		 * 修改用户头像
		 * @param commit
		 * @param params
		 */
		modifyAvatar ({ commit }, params) {
			api.account.modifyAvatar(params).then(response => {
				commit(types.SET_USER_AVATAR, response.data);
			});
		},
		/**
		 * 修改用户密码
		 * @param commit
		 * @param params
		 */
		showModifyPassword ({ commit }, params) {
			commit(types.SET_MODIFY_PASSWORD_FROM, params);
		},
		/**
		 * 注销登录
		 * @param commit
		 */
		logout ({ commit }) {
			api.account.logout().then(response => {
				commit(types.SET_ACCESS_TOKEN, null);
				commit(types.SET_USER, null);
			})
		},

	}
}
